package com.company.project.robot.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.company.project.robot.emum.RequestTypeEnum;
import com.company.project.robot.entity.*;
import com.company.project.robot.sdk.Api;
import com.company.project.robot.service.*;
import com.company.project.robot.utils.OpenAiUtils;
import com.company.project.sys.service.RedisService;
import com.theokanning.openai.completion.CompletionChoice;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;


/**
 * @author ZYF
 * @date 2021/10/28 15:24
 */
@Service
@Slf4j
public class DispatchServiceImpl {

    @Resource
    WechatGroupService wechatGroupService;

    @Resource
    IdiomService idiomService;

    @Resource
    LanternRiddlesService lanternRiddlesService;

    @Resource
    DialogueService dialogueService;

    @Resource
    RobotService robotService;

    @Resource
    JokesService jokesService;

    @Autowired
    CityServiceImpl cityService;


    @Autowired
    RedisService redisService;


    @Value("${cat.http.api}")
    private String apiUrl;

    public void sendMsg(ReceiveEntity receive) throws IOException {


        log.info("接收到的微信信息：：{}",JSON.toJSONString(receive));
        RequestTypeEnum requestTypeEnum = RequestTypeEnum.map.get(receive.getEvent());
        if(null != requestTypeEnum ){
            switch (requestTypeEnum){
                case EventFriendMsg:
                    StringBuilder msg =new StringBuilder();

                    List<CompletionChoice> questionAnswer = OpenAiUtils.getQuestionAnswer(receive.getMsg());
                    if(!questionAnswer.isEmpty()){
                        for (CompletionChoice completionChoice : questionAnswer) {
                            msg.append(completionChoice.getText());
                        }
                    }
                    Api.send_text_msg(apiUrl,receive.getRobot_wxid(),receive.getFrom_wxid(),msg.toString());
                    break;
                default:
                    break;
            }
        }

    }

    public void test(){
        List<CompletionChoice> questionAnswer = OpenAiUtils.getQuestionAnswer("JAVA底层原理");
        for (CompletionChoice completionChoice : questionAnswer) {
            System.out.println(completionChoice.getText());
        }
    }




//    private final static String apiUrl = "http://192.168.8.129:8073/send";


//    public void disp(SendMsgEntity msg) throws Exception {
//
//        RequestTypeEnum requestTypeEnum = RequestTypeEnum.map.get(msg.getType());
//        log.info(JSON.toJSONString(msg));
//        try {
//            String msgTypeDesc = msg.getMsgType() == 0 ? "未知" : MsgTypeEnum.map.get(msg.getMsgType()).getDesc();
//            log.info("收到msg，事件code: " + requestTypeEnum.getType() + " (" + requestTypeEnum.getDesc() + " - " + msgTypeDesc + ") msg: " + msg.getMsg());
//        } catch (Exception ex) {
//            log.error("报错了" + ex);
//        }
//        //检查是否有该群
//        WechatGroupEntity wechatGroup = wechatGroupService.getById(msg.getFromWxid());
//        switch (requestTypeEnum) {
//            case PRIVATE:
////                Api.send_text_msg(apiUrl, msg.getRobotWxid(), msg.getFromWxid(), "你好");
//                break;
//            case GROUP:
//                //判断是否有这个群聊，没有就添加到数据库,有就修改群名称
//                if (null == wechatGroup) {
//                    WechatGroupEntity wechat = new WechatGroupEntity();
//                    log.info("=========新建的群=============");
//                    log.info(JSON.toJSONString(msg.getFromName()));
//                    wechat.setGroupName(msg.getFromName());
//                    wechat.setId(msg.getFromWxid());
//                    wechat.setIsDenMi(0);
//                    wechat.setIsIdiom(0);
//                    wechat.setNumber(0);
//                    wechat.setDeleted(1);
//                    wechat.setRobotId(msg.getRobotWxid());
//                    wechatGroupService.save(wechat);
//                } else {
//                    Boolean bool = false;
//                    if (!wechatGroup.getGroupName().equals(msg.getFromName())) {
//                        wechatGroup.setGroupName(msg.getFromName());
//                        bool = true;
//                    }
//                    if (null != wechatGroup.getRobotId() || !wechatGroup.getRobotId().equals(msg.getRobotWxid())) {
//                        wechatGroup.setRobotId(msg.getRobotWxid());
//                        bool = true;
//                    }
//                    if (bool) {
//                        wechatGroupService.updateById(wechatGroup);
//                    }
//                }
//               //新建的群没有这些参数，不做处理
//                if (null != wechatGroup) {
//                    //游戏玩到第10轮结束
//                    if (wechatGroup.getNumber() >= 10) {
//                        wechatGroup.setIsDenMi(0);
//                        wechatGroup.setNumber(0);
//                        wechatGroup.setIsIdiom(0);
//                        wechatGroupService.updateById(wechatGroup);
//                        Api.send_text_msg(apiUrl, msg.getRobotWxid(), msg.getFromWxid(), "游戏结束啦[庆祝][庆祝][庆祝]");
//                    }
//                    //成语接龙游戏正在运行
//                    if (wechatGroup.getIsIdiom() == 1) {
//                        if (msg.getMsg().equals("结束成语接龙") || wechatGroup.getNumber() >= 10) {
//                            wechatGroup.setIsIdiom(0);
//                            wechatGroup.setNumber(0);
//                            wechatGroupService.updateById(wechatGroup);
//                            redisService.del(msg.getFromWxid());
//                            Api.send_group_at_msg(apiUrl, msg.getRobotWxid(), msg.getFromWxid(), msg.getFinalFromWxid(), msg.getFinalFromName(), "成语接龙环节结束啦[庆祝][庆祝][庆祝]");
//                        }
//                        //判断四个字的输入是否是成语
//                        else if (msg.getMsg().length() == 4) {
//                            if (msg.getMsg().equals("成语接龙")) {
//
//                            } else {
//                                Boolean bool = false;
//                                String senMsg = null;
//                                IdiomEntity entity = JSONObject.parseObject(redisService.get(msg.getFromWxid()), IdiomEntity.class);
//                                LambdaQueryWrapper<IdiomEntity> queryWrapper = Wrappers.lambdaQuery();
//                                queryWrapper
//                                        .like(IdiomEntity::getWordS, entity.getWordE())
//                                        .or()
//                                        .like(IdiomEntity::getPinyinS, entity.getWordE());
//                                List<IdiomEntity> list = idiomService.list(queryWrapper);
//                                String worldE = "";
//                                for (IdiomEntity idiom : list) {
//                                    if (idiom.getWord().equals(msg.getMsg())) {
//                                        bool = true;
//                                        worldE = idiom.getWordE();
//                                        redisService.del(msg.getFromWxid());
//                                        redisService.set(msg.getFromWxid(), JSON.toJSONString(idiom));
//                                        Integer number = wechatGroup.getNumber() + 1;
//                                        wechatGroup.setNumber(number);
//                                        wechatGroupService.updateById(wechatGroup);
//                                        break;
//                                    }
//                                }
//                                if (bool) {
//                                    senMsg = "恭喜接龙成功[庆祝][庆祝]\\n"+
//                                            "接下来请以["+worldE+"]开头接龙[加油][加油][加油]";
//                                } else {
//                                    senMsg = msg.getMsg() + "不是" + entity.getWordE() + "开头的成语";
//                                }
//                                Api.send_group_at_msg(apiUrl, msg.getRobotWxid(), msg.getFromWxid(), msg.getFinalFromWxid(), msg.getFinalFromName(), senMsg);
//                            }
//                        }
//                    }
//                    //灯谜游戏正在运行
//                    if (wechatGroup.getIsDenMi() == 1) {
//                        if (msg.getMsg().equals("结束猜灯谜")) {
//                            wechatGroup.setIsDenMi(0);
//                            wechatGroup.setNumber(0);
//                            wechatGroupService.updateById(wechatGroup);
//                            redisService.del(msg.getFromWxid());
//                            Api.send_group_at_msg(apiUrl, msg.getRobotWxid(), msg.getFromWxid(), msg.getFinalFromWxid(), msg.getFinalFromName(), "灯谜环境提前结束啦！！！");
//                            break;
//                        }
//                        LanternRiddlesEntity lanternEntity = JSONObject.parseObject(redisService.get(msg.getFromWxid()), LanternRiddlesEntity.class);
//                        if (msg.getMsg().equals(lanternEntity.getAnswer())) {
//                            Api.send_group_at_msg(apiUrl, msg.getRobotWxid(), msg.getFromWxid(), msg.getFinalFromWxid(), msg.getFinalFromName(), "恭喜小伙伴答对啦！！！");
//                            List<LanternRiddlesEntity> list = lanternRiddlesService.list();
//                            int max = list.size(), min = 0;
//                            int ran = (int) (Math.random() * (max - min) + min);
//                            String msg1 = list.get(ran).getRiddle();
//                            String answer = list.get(ran).getAnswer();
//                            if (StrUtil.isNotEmpty(redisService.get(msg.getFromWxid()))) {
//                                redisService.del(msg.getFromWxid());
//                            }
//                            redisService.set(msg.getFromWxid(), answer);
//                            Integer number = wechatGroup.getNumber() + 1;
//                            wechatGroup.setNumber(number);
//                            wechatGroupService.updateById(wechatGroup);
//                            Api.send_text_msg(apiUrl, msg.getRobotWxid(), msg.getFromWxid(), msg1);
//                        }
//                    }
//                }
//
//                //进入闲聊模式
////                if(wechatGroup.get()==1){}
//
//                //关键字回复
//                //缓存到redis里面
//                List<DialogueEntity> dialogueEntityList = new ArrayList<>();
//                if (StrUtil.isEmpty(redisService.get("dialogueList"))) {
//                    dialogueEntityList = dialogueService.list();
//                    redisService.set("dialogueList", JSON.toJSONString(dialogueEntityList));
//                } else {
//                    dialogueEntityList = JSON.parseArray(redisService.get("dialogueList"), DialogueEntity.class);
//                }
//                for (DialogueEntity dialogueEntity : dialogueEntityList) {
//                    if (dialogueEntity.getIsMatch() == 1) {
//                        if (dialogueEntity.getProblem().equals(msg.getMsg())) {
//                            Api.send_text_msg(apiUrl, msg.getRobotWxid(), msg.getFromWxid(), dialogueEntity.getAnswer());
//                            break;
//                        }
//                    } else {
//                        if (msg.getMsg().indexOf(dialogueEntity.getProblem()) != -1) {
//                            Api.send_text_msg(apiUrl, msg.getRobotWxid(), msg.getFromWxid(), dialogueEntity.getAnswer());
//                            break;
//                        }
//                    }
//                }
//                //天气回复
//                if (msg.getMsg().indexOf("天气") != -1) {
//                    String sendMsg = null;
//                    try {
//                        HashMap<String, String> map = cityService.getWeatherInfo(msg.getMsg().replaceFirst("天气", ""));
//                        sendMsg = "【" + map.get("city") + "天气[太阳]】\\n"
//                                + "今天：" + map.get("type") + "，"
//                                + "最高温度：" + map.get("high").replaceFirst("高温", "") + "，"
//                                + "最低温度：" + map.get("low").replaceFirst("低温", "") + "，"
//                                + "风向：" + map.get("fengxiang") + "\\n"
//                                + "明天：" + map.get("type1") + "，"
//                                + "最高温度：" + map.get("high1").replaceFirst("高温", "") + "，"
//                                + "最低温度：" + map.get("low1").replaceFirst("低温", "") + "，"
//                                + "风向：" + map.get("fengxiang1");
//
//                    } catch (Exception ex) {
//                        sendMsg = "[皱眉]指令错误，正确指令：城市+天气 \\n 【ps：暂时不支持国外的天气查询】";
//                    }
//                    Api.send_text_msg(apiUrl, msg.getRobotWxid(), msg.getFromWxid(), sendMsg);
//                }
//                //进入猜灯谜环节
//                else if (msg.getMsg().indexOf("猜灯谜") != -1) {
//                    if (wechatGroup.getIsDenMi() == 1) {
//                        LanternRiddlesEntity lanternEntity = JSONObject.parseObject(redisService.get(msg.getFromWxid()), LanternRiddlesEntity.class);
//                        Api.send_text_msg(apiUrl, msg.getRobotWxid(), msg.getFromWxid(), "正在进行猜灯谜环节! \\n ——————————— \\n 题目为：【"+ lanternEntity.getRiddle()+"】");
//                    } else if (wechatGroup.getIsIdiom() == 1) {
//                        IdiomEntity entity = JSONObject.parseObject(redisService.get(msg.getFromWxid()), IdiomEntity.class);
//                        Api.send_text_msg(apiUrl, msg.getRobotWxid(), msg.getFromWxid(), "正在进行成语接龙！！！ \\n ——————————— \\n 请以【"+entity.getWordE()+"】开头的成语，继续接龙");
//                    } else {
//                        List<LanternRiddlesEntity> lanternRiddlesList = new ArrayList<>();
//                        if (StrUtil.isNotEmpty(redisService.get("lanternRiddlesList"))) {
//                            lanternRiddlesList = JSON.parseArray(redisService.get("lanternRiddlesList"), LanternRiddlesEntity.class);
//                        } else {
//                            lanternRiddlesList = lanternRiddlesService.list();
//                            redisService.set("lanternRiddlesList", JSON.toJSONString(lanternRiddlesList));
//                        }
//                        int max = lanternRiddlesList.size(), min = 0;
//                        int ran = (int) (Math.random() * (max - min) + min);
//                        String msg1 = lanternRiddlesList.get(ran).getRiddle();
//                        String answer = lanternRiddlesList.get(ran).getAnswer();
//                        if (StrUtil.isNotEmpty(redisService.get(msg.getFromWxid()))) {
//                            redisService.del(msg.getFromWxid());
//                        }
//                        redisService.set(msg.getFromWxid(), JSON.toJSONString(lanternRiddlesList.get(ran)));
//                        wechatGroup.setIsDenMi(1);
//                        wechatGroup.setNumber(1);
//                        wechatGroupService.updateById(wechatGroup);
//                        Api.send_text_msg(apiUrl, msg.getRobotWxid(), msg.getFromWxid(), "灯谜环节开始啦[加油] \\n ——————————— \\n 请接招：【" + msg1 + "】");
//                    }
//                }
//                //进入成语接龙环节
//                else if (msg.getMsg().equals("成语接龙")) {
//                    if (wechatGroup.getIsDenMi() == 1) {
//                        LanternRiddlesEntity lanternEntity = JSONObject.parseObject(redisService.get(msg.getFromWxid()), LanternRiddlesEntity.class);
//                        Api.send_text_msg(apiUrl, msg.getRobotWxid(), msg.getFromWxid(), "正在进行猜灯谜环节! \\n ——————————— \\n 题目为：【"+ lanternEntity.getRiddle()+"】");
//                    } else if (wechatGroup.getIsIdiom() == 1) {
//                        IdiomEntity entity = JSONObject.parseObject(redisService.get(msg.getFromWxid()), IdiomEntity.class);
//                        Api.send_text_msg(apiUrl, msg.getRobotWxid(), msg.getFromWxid(), "正在进行成语接龙！！！ \\n ——————————— \\n 请以【"+entity.getWordE()+"】为开头的成语，进行成语接龙");
//                    } else {
//                        List<IdiomEntity> list = idiomService.list();
//                        int max = list.size(), min = 0;
//                        int ran = (int) (Math.random() * (max - min) + min);
//                        String sendMsg = "成语：" + list.get(ran).getWord() + "\\n" +
//                                "含义：" + list.get(ran).getRemark();
//                        if (StrUtil.isNotEmpty(redisService.get(msg.getFromWxid()))) {
//                            redisService.del(msg.getFromWxid());
//                        }
//                        redisService.set(msg.getFromWxid(), JSON.toJSONString(list.get(ran)));
//                        wechatGroup.setIsIdiom(1);
//                        wechatGroup.setNumber(1);
//                        wechatGroupService.updateById(wechatGroup);
//                        Api.send_text_msg(apiUrl, msg.getRobotWxid(), msg.getFromWxid(), "成语接龙开始了哦，一共10道题[加油][加油]");
//                        Api.send_text_msg(apiUrl, msg.getRobotWxid(), msg.getFromWxid(), sendMsg);
//                    }
//                }
//                else if(msg.getMsg().indexOf("笑话") != -1){
//                    List<JokesEntity> jokesEntityList = new ArrayList<>();
//                    if(StrUtil.isEmpty(redisService.get("jokes"))){
//                        jokesEntityList= jokesService.list();
//                        redisService.set("jokes",JSON.toJSONString(jokesEntityList));
//                    }else{
//                        jokesEntityList = JSON.parseArray(redisService.get("jokes"), JokesEntity.class);
//                    }
//                    int max=jokesEntityList.size(),min=0;
//                    int ran = (int) (Math.random()*(max-min)+min);
//                    String msg1 = jokesEntityList.get(ran).getTEXT();
//                    Api.send_text_msg(apiUrl,msg.getRobotWxid(),msg.getFromWxid(),msg1);
//                }
//                break;
//            case UNKNOW:
//                break;
//            case MEMBER_ADD:
//                //新人进群
//                JSONObject obj = JSONObject.parseObject(msg.getMsg());
//                JSONObject object = JSONObject.parseObject(obj.getJSONArray("guest").get(0).toString());
//                Api.send_group_at_msg(apiUrl, msg.getRobotWxid(), msg.getFromWxid(),
//                        object.getString("wxid"), null,
//                        wechatGroup.getWelcome());
//                break;
//            case MEMBER_DEC:
//                break;
//            case VERFIGY:
//                break;
//            case SCAN_CASH_MONEY:
//                break;
//            case TRANSFER:
//                break;
//            case STARTUP:
//                break;
//            case LOGIN_SUCC:
//                //插件刚登录的时候检查是否有这个微信号，没有就放入数据库，有就修改
//                RobotEntity robotEntity = robotService.getById(msg.getRobotWxid());
//                if (null != robotEntity) {
//                    robotEntity.setName(JSONObject.parseObject(JSONObject.toJSONString(msg)).getJSONObject("msg").getString("nickname"));
//                    robotService.updateById(robotEntity);
//                } else {
//
//                    robotEntity.setId(msg.getRobotWxid());
//                    robotEntity.setName(JSONObject.parseObject(JSONObject.toJSONString(msg)).getString("nickname"));
//                    robotEntity.setDeleted(1);
//                    robotService.save(robotEntity);
//                }
//                break;
//            case LOGIN_OFF:
//                break;
//            default:
//                break;
//        }
//    }


}
